#!/bin/bash
IFS=' '
BASE_DIR=/opt/iptables                  # iptables脚本目录
COMPANY_IP=175.42.20.0/26               # 公司IP
CONTROL_PUB=106.75.84.220               # 控制机IP
CONTROL_INNER=10.19.16.147              # 控制机内网IP
BACKUPSERVER_PUB=117.50.108.203         # 备份机IP
BACKUPSERVER_INNER=10.19.169.224        # 备份机内网IP
ZABBIX_IP=110.43.47.95                  # zabbix监控服务器IP
SSHD_PORT=`netstat -tnpl|grep sshd|grep 0.0.0.0 |cut -d":" -f2|cut -d" " -f1`       # 识别本机的ssh端口号
INNER_NET=(192.168.100.0 192.168.99.0 192.168.98.0)     # 需要放行的内网IP网段
ALLOW_INNER_IP=(192.168.0.0)

# 运行日志记录函数
mkdir -p ${BASE_DIR}/logs
RUN_LOG=${BASE_DIR}/logs/error_$(date +'%Y%m%d').log
function logger(){
    # 日志记录函数，使用方式：
    # logger [INFO|ERROR|WARNING|DEGUG] "msg"
    DATE_NOW=`date +'%Y-%m-%d %H:%M:%S'`
    LOG_DEVEL=${1}
    LOG_STRING=${2}
    case "${LOG_DEVEL}" in
        error|ERROR)
            echo -e "${DATE_NOW} [ERROR]:${LOG_STRING}" | tee -a ${RUN_LOG}
            ;;
        info|INFO)
            echo -e "${DATE_NOW} [INFO]:${LOG_STRING}" | tee -a ${RUN_LOG}
            ;;
        warning|WARNING)
            echo -e "${DATE_NOW} [WARNING]:${LOG_STRING}" | tee -a ${RUN_LOG}
            ;;
        debug|DEGUG)
            echo -e "${DATE_NOW} [DEGUG]:${LOG_STRING}" | tee -a ${RUN_LOG}
            ;;
    esac
}



# 判断目标服务器的操作系统是CentOS6/7。其他linux系统未做过测试。
SERVER_OS=
function isCentOS() {
    if [[ -f /etc/redhat-release ]];then
        if [[ -n "`grep 'release 6' /etc/redhat-release`" ]];then
            SERVER_OS=centos6
            logger "INFO" "The SERVER OS is ${SERVER_OS}."
        elif [[ -n "`grep 'release 7' /etc/redhat-release`" ]];then
            SERVER_OS=centos7
            logger "INFO" "The SERVER OS is ${SERVER_OS}."
        else
            logger "ERROR" "The SERVER OS is not CentOS6 or CentOS7."
            exit 1
        fi
    else
        logger "ERROR" "The SERVER OS is not CentOS."
        exit 1
    fi
}
isCentOS


# 安装 iptables,iptables-services
function install_iptables(){
    if [[ `rpm -qa|grep iptables|wc -l` -lt 2 ]];then
        yum install iptables iptables-services -y
    fi
}
install_iptables


# 获取本机的公网IP、内网IP、网卡名称
PUBLIC_IP=
INNER_IP=
INNER_IF=
function getIp(){
    IP_BIN=`whereis ip|awk -F'[: ]' '{print $3}'`
    if [[ -n "`grep 'release 7' /etc/redhat-release`" ]];then
        INNER_IF=`/sbin/ifconfig |grep -P -B1 "inet 10\.|inet 192\.168\.|inet 172\.((1[6-9])|(2[0-9])|(3[0-1]))\."|grep -v docker|grep flags|grep -v br-|head -1|cut -d':' -f1`
        if [[ `${IP_BIN} addr show ${INNER_IF}|grep -Po 'inet \K[\d.]+'|wc -l` -eq 1 ]];then
            INNER_IP=$(${IP_BIN} addr show ${INNER_IF}|grep -Po 'inet \K[\d.]+')
        else
            INNER_IP=`/sbin/ifconfig ${INNER_IF}|grep -Po 'inet \K[\d.]+'|head -1`
        fi
        PUBLIC_IP=`/sbin/ifconfig |grep "inet "|grep -P -v "inet 127\.0\.0\.1|inet 10\.|inet 192\.168\.|inet 172\.((1[6-9])|(2[0-9])|(3[0-1]))\."|head -1|awk '{print $2}'`
    else
        INNER_IF=`/sbin/ifconfig |grep -P -B1 "inet addr:10\.|inet addr:192\.168\.|inet addr:172\.((1[6-9])|(2[0-9])|(3[0-1]))\."|grep -v docker|grep Link|head -1|cut -d' ' -f1|cut -d':' -f1`
        if [[ `${IP_BIN} addr show ${INNER_IF}|grep -Po 'inet \K[\d.]+'|wc -l` -eq 1 ]];then
            INNER_IP=$(${IP_BIN} addr show ${INNER_IF}|grep -Po 'inet \K[\d.]+')
        else
            INNER_IP=`/sbin/ifconfig ${INNER_IF}|grep -Po 'inet addr:\K[\d.]+'|head -1`
        fi
        PUBLIC_IP=`/sbin/ifconfig |grep "inet addr"|grep -P -v "inet addr:127\.0\.0\.1|inet addr:192\.168\.|inet addr:10\.|inet addr:172\.((1[6-9])|(2[0-9])|(3[0-1]))\."|head -1|awk '{print $2}' |sed "s/addr://g"`
    fi

    if [ -z "${PUBLIC_IP}" ];then
        W_PUBLIC_IP=`curl -s www.trackip.net/ip`        # 通过curl公网的开放接口获取本机出口IP
        if [[ "${W_PUBLIC_IP}" == "${COMPANY_IP}" ]];then
            PUBLIC_IP=${INNER_IP}
        else
            PUBLIC_IP=${W_PUBLIC_IP}
        fi
    fi
#    echo "PUBLIC_IP=${PUBLIC_IP} INNER_IP=${INNER_IP} INNER_IF=${INNER_IF}"
    logger "INFO" "PUBLIC_IP=${PUBLIC_IP} INNER_IP=${INNER_IP} INNER_IF=${INNER_IF}"
}
getIp


# 判断本机是否是公司内网服务器（192.168.x.x）
IS_INNER=
function isInner() {
    INNER_SEG=`echo ${INNER_IP}|cut -d'.' -f 1-3`
    for INNER_NET1 in ${INNER_NET[@]};
    do
        if [ ${INNER_SEG} == "${INNER_NET1%.*}" ];then
            IS_INNER=yes
            break
        fi
    done
}
isInner

# 优化iptables内核相关参数
DATE_NOW=`date +'%Y%m%d%H%M%S'`
# [[ ! -e /sbin/iptables ]] && yum -y install iptables iptables-services
if [ -f /sbin/iptables ]; then
    /sbin/service iptables save
    /usr/bin/cp /etc/sysconfig/iptables /etc/sysconfig/iptables.${DATE_NOW}
    [ `/sbin/lsmod|grep "nf_conntrack "|wc -l` -eq 0 ] && /sbin/modprobe nf_conntrack
    [[ -z `grep net.netfilter.nf_conntrack_max /etc/sysctl.conf` ]] && echo "net.netfilter.nf_conntrack_max = 9999999999" >> /etc/sysctl.conf
    [[ -z `grep net.netfilter.nf_conntrack_tcp_timeout_established /etc/sysctl.conf` ]] && echo "net.netfilter.nf_conntrack_tcp_timeout_established = 300" >> /etc/sysctl.conf
    [[ -z `grep net.netfilter.nf_conntrack_tcp_timeout_time_wait /etc/sysctl.conf` ]] && echo "net.netfilter.nf_conntrack_tcp_timeout_time_wait = 12" >> /etc/sysctl.conf
    [[ -z `grep net.netfilter.nf_conntrack_tcp_timeout_close_wait /etc/sysctl.conf` ]] && echo "net.netfilter.nf_conntrack_tcp_timeout_close_wait = 60" >> /etc/sysctl.conf
    [[ -z `grep net.netfilter.nf_conntrack_tcp_timeout_fin_wait /etc/sysctl.conf` ]] && echo "net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 120" >> /etc/sysctl.conf
    /sbin/sysctl -p
    echo 131072 > /sys/module/nf_conntrack/parameters/hashsize
    if [ ! -f /etc/modprobe.d/local.conf ];then
        echo "options nf_conntrack hashsize=131072" > /etc/modprobe.d/local.conf
    else
        if [ `grep hashsize /etc/modprobe.d/local.conf|wc -l` -eq 0 ];then
            echo "options nf_conntrack hashsize=131072" >> /etc/modprobe.d/local.conf
        fi
    fi
fi

# 清空 iptables filter表规则
/sbin/iptables -t filter -Z INPUT
/sbin/iptables -t filter -F INPUT
/sbin/iptables -t filter -Z OUTPUT
/sbin/iptables -t filter -F OUTPUT
[[ `grep -c "FORWARD.*icmp-host-prohibited" /etc/sysconfig/iptables` -ge 1 ]] && /sbin/iptables -t filter -Z FORWARD &&  /sbin/iptables -t filter -F FORWARD

# 配置 iptables filter表的默认行为为 ACCEPT
/sbin/iptables -t filter -P INPUT ACCEPT
/sbin/iptables -t filter -P OUTPUT ACCEPT
/sbin/iptables -t filter -P FORWARD ACCEPT

# 如果本机没有运行docker，可以清空 iptables nat表规则
if [[ `/sbin/iptables -t nat -nvL|grep -ci "docker"` -eq 0 ]];then
    /sbin/iptables -t nat -Z PREROUTING
    /sbin/iptables -t nat -F PREROUTING
    /sbin/iptables -t nat -Z OUTPUT
    /sbin/iptables -t nat -F OUTPUT
    /sbin/iptables -t nat -Z POSTROUTING
    /sbin/iptables -t nat -F POSTROUTING
fi

# 配置 iptables nat表的默认行为为 ACCEPT
/sbin/iptables -t nat -P PREROUTING ACCEPT
/sbin/iptables -t nat -P POSTROUTING ACCEPT
/sbin/iptables -t nat -P OUTPUT ACCEPT

# 配置iptables filter表默认放行规则
/sbin/iptables -A INPUT -i lo -p all -j ACCEPT
#/sbin/iptables -A OUTPUT -o lo -p all -j ACCEPT
/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
#/sbin/iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
/sbin/iptables -A INPUT  -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
/sbin/iptables -A INPUT  -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
######################### head END #########################